package com.cskaoyan.market.controller.wx;

import com.cskaoyan.market.db.domain.MarketAddress;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.wx.WxAddressService;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/address")
public class WxAddressController {
    @Autowired
    WxAddressService addressService;
    @Autowired
    SecurityManager securityManager;


    @GetMapping("list")
    //表示当前接口需要认证才能访问
    @RequiresAuthentication
    public Object list() {
        //通过securityManager获取session
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        Integer id = user.getId();
        List<MarketAddress> marketAddressList = addressService.list(id);
        return ResponseUtil.okList(marketAddressList);
    }

    @GetMapping("detail")
    @RequiresAuthentication
    public Object detail(Integer id) {
        if (id == null) {
            //如果未指定id，则提示参数不对
            return ResponseUtil.badArgument();
        }
        MarketAddress data = addressService.detail(id);
        return ResponseUtil.ok(data);
    }

    @PostMapping("save")
    @RequiresAuthentication
    public Object save(@RequestBody MarketAddress marketAddress) {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketUser user = (MarketUser) session.getAttribute("user");
        Integer userId = user.getId();
        marketAddress.setUserId(userId);
        //注意此处post的响应报文中存在data，data的数值为id，添加新数据时返回值即为新数据的id，直接获取即可
        int data = addressService.save(marketAddress);
        return ResponseUtil.ok(data);
    }

    @PostMapping("delete")
    @RequiresAuthentication
    public Object delete(@RequestBody Map map) {
        Integer id = (Integer) map.get("id");
        boolean delete = addressService.delete(id);
        //删除失败返回参数不对信息
        if (!delete) {
            return ResponseUtil.badArgument();
        }
        return ResponseUtil.ok();
    }
}

